import datetime
import json
import logging
import random
import threading
import os
import time
import requests
import uuid
from fake_useragent import UserAgent
from keep_token_alive import keep_token_alive

class Wechat_Spider():
    
    def __init__(self, cookie, token):
        self.user_agent = UserAgent().random
        self.cookie = cookie
        self.token = token 
        self.interval_time = 30 * 60 # 30分钟
        self.fake_id_dict = {'齐鲁晚报':'Mzg3OTgwODM2NA==','共青团中央':'MzA3NTE5MzQzMA==','中国政府网':'MzA4MDA0MzcwMA==',
                             '文旅济南':'Mzg5OTA5NTMyNw==','新华社':'MzA4NDI3NjcyNA==',
                             '济南市文化和旅游局':'MjM5OTk4NTU0MQ==','新闻坊':'MjM5NDM1NjY3MQ==',
                             '微泰州':'MjM5MjQyMDY1NQ=='}
    
    def main(self):
        headers = {
                    'User-Agent': self.user_agent,
                    'Cookie': self.cookie
                }
        while True:
            for k,v in self.fake_id_dict.items():
                data = []
                response = requests.get(url=f'https://mp.weixin.qq.com/cgi-bin/appmsgpublish?sub=list&search_field=null&begin=0&count=3&query=&fakeid={v}&type=101_1&free_publish_type=1&sub_action=list_ex&token={self.token}&lang=zh_CN&f=json&ajax=1', headers=headers)
                resp_json = response.json()
                if resp_json.get('base_resp',{'ret':200}).get('ret', 200) == 200013:
                    # TODO 联动数据库，将is_zombie设置为1，告诉存活程序，这个token和cookie失效了
                    print('error:')
                    print(resp_json)
                    return False
                
                try:
                    article_list = json.loads(resp_json['publish_page'])['publish_list']
                    for i_,v_ in enumerate(article_list):
                        v_['publish_info'] = json.loads(v_['publish_info'])
                        data += v_['publish_info']['appmsgex']
                        
                    path = f'./testwechat/{k}/'
                    if not os.path.exists(path):
                        # 如果文件夹不存在，则创建文件夹
                        os.makedirs(path)
                    with open(f'{path + str(datetime.datetime.now().strftime("%Y-%m-%d|%H:%M:%S"))}.json', "w") as json_file:
                        json.dump(data, json_file)
                except Exception as e:
                    print(str(e))
                time.sleep(random.randint(60,120))
            # time.sleep(30 * 60)
            time.sleep(random.randint(50 * 60, 60 * 60))
            print('开始新一次检查')


if __name__ == "__main__":
    cookie = 'data_bizuin=3918696977; slave_sid=WndFcGRvWDM4TUxDeWJFb3JiQnVrREF1R3JmNW12RmlDZmtXUnN5d1VzTWRoR1pnS3NHQWhza1QyRWVsOGhRaFlBbU1yRHZLZmdjQzFscXREU3gzamdNaVNRWXRJc2xlbVBSbVlsQ1QzRnBYdE5TOWFlcWdVNll1SmlNeWcyWHRyWm5mZW5pNmdRRjZ4cU5R; slave_user=gh_1469fb030616'
    token = '840091464'
    spider = Wechat_Spider(cookie=cookie,token=token)
    threads = []
    # threads.append(threading.Thread(target=keep_token_alive, args=(spider.user_agent,spider.token,spider.cookie)))
    threads.append(threading.Thread(target=spider.main))
    
    for i in threads:
        i.start()
    
    for i in threads:
        i.join()